﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Evpo.ContactData.Common;
using Evpo.ContactData.Data;

namespace Evpo.ContactData.ViewModel
{
    public class ContactListViewModel : ListViewModel
    {
        #region Consts
        #endregion

        public ContactListViewModel(
            ModelFactory factory, IConnection conn, 
            ContactQueryParameters queryParameters, int pageCount)
            : base(pageCount)
        {
            _contactAdapter = factory.CreateContactAdapter(conn);
            _titleAdapter = factory.CreateTitleAdapter(conn);
            ContactQuery = queryParameters;
        }


        #region Properties
        public override ListQueryParameters ListQuery
        {
            get { return ContactQuery; }
        }

        protected override AdapterBase Adapter
        {
            get { return _contactAdapter; }
        }

        public ContactQueryParameters ContactQuery
        {
            get;
            private set;
        }

        #endregion

        #region Fields
        private readonly ContactAdapter _contactAdapter;
        private readonly TitleAdapter _titleAdapter;
        
        
        #endregion

        #region Methods

        public void SetPageCount(int count)
        {
            PageCount = count;
        }

        public void ResetQuery()
        {
            DataSource = null;
        }

        public override object QueryResultAsDataSource()
        {
            return AllContacts();
        }

        private List<ContactListItem> AllContacts()
        {
            List<ContactListItem> retVal = null;

            if (DataSource == null)
            {
                int contactCount;
                retVal = ContactListViewModel.ContactsToContactListItems(
                    _contactAdapter.QueryContacts(ContactQuery, out contactCount),
                    _titleAdapter);

                this.ItemCount = contactCount;
                DataSource = retVal;
            }
            return retVal;
        }

        internal static List<ContactListItem> ContactsToContactListItems(
            List<Contact> contacts, TitleAdapter titleAdapter)
        {
            return
                (from contact in contacts
                 select new ContactListItem()
                 {
                     Contact = contact,
                     TitleName = titleAdapter.GetItem(contact.TitleID).Name
                 }).ToList();
        }

        #endregion


    }
}
